package com.longway.common.ext.directive;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.TemplateException;
import com.jfinal.template.expr.ast.Expr;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;
 
import java.text.DecimalFormat;
 
public class Number2Directive extends Directive {
 
   private Expr valueExpr;
   private Expr patternExpr;
   private int paraNum;
 
   @Override
   public void setExprList(ExprList exprList) {
      this.paraNum = exprList.length();
      if (paraNum == 0) {
         throw new ParseException("The parameter of #number directive can not be blank", location);
      }
      if (paraNum > 2) {
         throw new ParseException("Wrong number parameter of #number directive, two parameters allowed at most", location);
      }
 
      if (paraNum == 1) {
         this.valueExpr = exprList.getExpr(0);
         this.patternExpr = null;
      } else if (paraNum == 2) {
         this.valueExpr = exprList.getExpr(0);
         this.patternExpr = exprList.getExpr(1);
      }
   }
 
   @Override
   public void exec(Env env, Scope scope, Writer writer) {
      Object value = valueExpr.eval(scope);
      if (value == null) {
         return ;
      }
 
      if (paraNum == 1) {
         outputWithoutPattern(writer, value);
      } else if (paraNum == 2) {
         outputWithPattern(scope, writer, value);
      }
   }
 
   private void outputWithoutPattern(Writer writer, Object value) {
//    String ret = new DecimalFormat().format(value);
      //加入默认格式化为 千位符 以及保留两位小数
      String ret = new DecimalFormat((String)"#,###.##").format(value);
      write(writer, ret);
   }
 
   private void outputWithPattern(Scope scope, Writer writer, Object value) {
      Object pattern = patternExpr.eval(scope);
      if ( !(pattern instanceof String) ) {
         throw new TemplateException("The sencond parameter pattern of #number directive must be String", location);
      }
 
      String ret = new DecimalFormat((String)pattern).format(value);
      write(writer, ret);
   }
}